package com.ds.robot.assistant.job;

import com.ds.robot.assistant.component.MessageSender;
import com.ds.robot.assistant.enums.Env;
import com.ds.robot.assistant.service.HolidayServiceContext;
import com.ds.robot.assistant.service.impl.TargetAchievementServiceImpl;
import com.ds.robot.assistant.service.impl.TargetOkrServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Service
@Slf4j
public class OkrTipJob {

    @Value("${app.quarter:2024H2}")
    private String quarter;

    @Autowired
    private HolidayServiceContext holidayServiceContext;

    private final TargetAchievementServiceImpl targetAchievementService;
    private final TargetOkrServiceImpl targetOkrService;
    private final MessageSender messageSender;

    public OkrTipJob(TargetOkrServiceImpl targetOkrService, MessageSender messageSender, TargetAchievementServiceImpl targetAchievementService) {
        this.targetOkrService = targetOkrService;
        this.messageSender = messageSender;
        this.targetAchievementService = targetAchievementService;
    }

    /**
     * 加盟商业绩：2024年以后开店时间满三个月加盟商门店的前三个月平均业绩
     * 岗位职称里带 扶商和管理 字的加盟商人员，在过去一周的平均登录次数
     * 岗位职称里带 老板 字的加盟商人员，在过去一周的平均登录次数
     * 数仓每周日上午9点跑数据，约半小时完成
     */
    @Scheduled(cron = "0 25 7 ? * MON")
    public void sendOkrAchievementJobTest() {
        log.info("开始发送OKR报告到测试群");
        String message = targetOkrService.getOkrReportMessage(quarter);
        if (StringUtils.hasText(message)) {
            messageSender.sendMessage(message, Env.TEST);
        }
    }

    @Scheduled(cron = "0 0 9 * * MON")
    public void sendOkrAchievementJob() {
        if (holidayServiceContext.isRestDay(LocalDate.now().toString())) {
            log.info("今天是休息日，不发OKR报告");
            return;
        }
        log.info("开始发送正式OKR报告");
        String message = targetOkrService.getOkrReportMessage(quarter);
        if (StringUtils.hasText(message)) {
            messageSender.sendMessage(message, Env.TEST);
            messageSender.sendMessage(message, Env.PROD);
        }
    }

    @Scheduled(cron = "0 0 14,17,20 * * SUN")
    public void checkData() {
        log.info("开始检查OKR数据");
        try {
            targetAchievementService.checkAndProcessData();
        } catch (Exception e) {
            log.error("检查和更新OKR数据异常", e);
            messageSender.sendMessage("检查和更新OKR数据发生异常：" + e.getMessage(), Env.TEST);
            messageSender.sendMessage("检查和更新OKR数据发生异常：" + e.getMessage(), Env.DATA_WAREHOUSE);
        }
    }
}
